import 'dart:io';
import 'package:book_manager_app/app/utils/widget/my_dialog.dart';
import 'package:book_manager_app/utils/common/user/user_info.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../../modules/login/bindings/login_binding.dart';
import '../../modules/login/views/login_view.dart';
import 'package:path_provider/path_provider.dart';
import 'const.dart';

class DeviceInfo {
  // 设备唯一标识, 等通iOS的uuid,Android的id
  // 这是一个设备特定的64位标识符，在Android设备首次启动时生成。每次设备恢复出厂设置时，ID会重置。
  // 在Android 8.0及更高版本中，对于每个新的应用安装，此标识符都是不同的。
  String id = "";
  String model = "";                      // 设备型号, 例如“iPhone”和“iPod touch”。
  String brand = "";                      // 设备品牌, 例如: 华为、苹果、小米
  String deviceName = "";                 // 硬件名称: 例如iPhone 6 Plus
  bool isPhysicalDevice = false;          // 是否是真机(物理设备)
  String systemVersion = "";              // 系统版本

  DeviceInfo(this.id, this.model, this.brand, this.deviceName, this.systemVersion, this.isPhysicalDevice);
}

class AppManager {
  // 单例
  // AppManager._share();
  // static final AppManager _instance = AppManager._share();
  // static AppManager get instance { return _instance;}

  static bool isLogin = false;
  // 设备信息
  static late final DeviceInfo _deviceInfo;
  static ImageProvider? launchImage; // app启动图
  static bool isShowUpload = false; // 记录更新提示的弹出框，避免重复叠加弹框。
  
  static int storeId = 0; // 当前登录的店铺id

  static get uuid => _deviceInfo.id;
  // 设备型号, 例如“iPhone”和“iPod touch”。
  static get model => _deviceInfo.model;
  // 设备品牌, 例如: 华为、苹果、小米
  static get brand => _deviceInfo.brand;
  // 硬件名称: 例如iPhone 6 Plus
  static get deviceName => _deviceInfo.deviceName;
  // 是否是真机(物理设备)
  static get isPhysicalDevice => _deviceInfo.isPhysicalDevice;
  // 系统版本
  static get systemVersion => _deviceInfo.systemVersion;

  // 存取 userToken
  static get userToken => localStorageRead(USER_TOKEN);
  static set userToken(value) => localStorageWrite(USER_TOKEN, value);

  // 首次安装返回true （同意隐私协议后，则返回false，默认为true）
  static bool get isFirstInstall => localStorageRead(IS_FIRST_INSTALL) ?? true;
  static set isFirstInstall(bool value) => localStorageWrite(IS_FIRST_INSTALL, value);

  // 认证状态
  static bool get auth => localStorageRead("native_auth") ?? false;
  static set auth(bool auth) => localStorageWrite(kUserInfo, auth);

// ===============================================================================
//                      本地用户信息
// ===============================================================================
  static removeUserAccount() async => await localStorageRemove(kUserInfo);
  static UserModel? get userInfo => UserModel.fromJson(localStorageRead(kUserInfo));
  static set userInfo(UserModel? account) => localStorageWrite(kUserInfo, account?.toJson());


// ===============================================================================
//                      当前的店铺信息
// ===============================================================================
  static removeShopModel() async => await localStorageRemove(kShopInfo);
  static ShopInfo? get shopInfo => localStorageRead(kShopInfo);
  static set shopInfo(ShopInfo? shop) => localStorageWrite(kShopInfo, shop);




  static getDeviceInfo() async {
    final DeviceInfoPlugin device = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo android = await device.androidInfo;
      _deviceInfo = DeviceInfo(android.id, android.model, "", android.brand, "", android.isPhysicalDevice);
    } else if (Platform.isIOS) {
      IosDeviceInfo ios = await device.iosInfo;
      String deviceName = getIphoneModel(ios.utsname.machine);
      _deviceInfo = DeviceInfo(ios.identifierForVendor!, ios.model, "Apple", deviceName, ios.systemVersion, ios.isPhysicalDevice);

    }
    debugPrint("getDeviceInfo() 执行完毕！");
    debugPrint("当前设备品牌：${AppManager.brand}");
    debugPrint("当前设备型号：${AppManager.model}");
    debugPrint("当前设备名称：${AppManager.deviceName}");
    debugPrint("当前设备UUID：${AppManager.uuid}");
    debugPrint("当前设备是否为模拟器：${AppManager.isPhysicalDevice?"否":"是"}");
  }


  static Future<void> deleteDirectory(FileSystemEntity file) async {
    // PermissionStatus status = await Permission.storage.status;
    if (file is Directory && file.existsSync()) {
      debugPrint(file.path);
      final List<FileSystemEntity> children =
      file.listSync(recursive: true, followLinks: true);
      for (final FileSystemEntity child in children) {
        await deleteDirectory(child);
      }
    }
    try {
      if (file.existsSync()) {
        await file.delete(recursive: true);
      }
    } catch (err) {
      // debugPrint(err);
    }
  }

  //循环获取缓存大小
  static Future getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    //  File
    if (file is File && file.existsSync()) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory && file.existsSync()) {
      List children = file.listSync();
      double total = 0;
      if (children.isNotEmpty)
        // ignore: curly_braces_in_flow_control_structures
        for (final FileSystemEntity child in children) {
          total += await getTotalSizeOfFilesInDir(child);
        }
      return total;
    }
    return 0;
  }

  /// 获取缓存
  static Future<String> findCacheSumSize() async {
    final tempDir = await getTemporaryDirectory();
    double cache = await AppManager.getTotalSizeOfFilesInDir(tempDir);
    return formatSize(cache);
  }

  /// 删除缓存
  static clearApplicationCache() async {
    final tempDir = await getTemporaryDirectory();
    showLoadingMessage("清除中...");
    await AppManager.deleteDirectory(tempDir);
    dismissLoading();
    showMessage("清除成功");
  }

  /// 缓存大小格式转换
  static String formatSize(double value) {
    // ignore: unnecessary_null_comparison
    if (value == null) {
      return '0';
    }
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  // 退出登录
  static signOut() {
    AppManager.isLogin = false;
    AppManager.removeShopModel();
    AppManager.removeUserAccount();
    Get.offAll(()=> const LoginView(), binding: LoginBinding(), transition: Transition.noTransition);
  }

}

// ===============================================================================
//                AppManager 常用模型
// ===============================================================================
class ShopInfo {
  String? shopName;
  String? shopId;
  ShopInfo({this.shopName, this.shopId});
  factory ShopInfo.fromJson(Map<String, dynamic> json) {
    return ShopInfo(
      shopName: json['shopName'],
      shopId: json['shopId'],
    );
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['shopName'] = shopName;
    data['shopId'] = shopId;
    return data;
  }
}



// ===============================================================================
//                                    本地存储
// ===============================================================================
GetStorage box = GetStorage();
localStorageWrite(String key, dynamic value) {
  box.write(key, value);
}
T? localStorageRead<T>(String key) {
  return box.read(key);
}
localStorageRemove(String key) {
  box.remove(key);
}
// ===============================================================================
//                                    本地存储
// ===============================================================================



// ===============================================================================
//                       获取 iOS 设备型号名称
// ===============================================================================
String getIphoneModel(String machine) {
  return _iOSModels[machine] ?? machine;
}
const _iOSModels = {
  "i386": "iPhone Simulator",
  "x86_64": "iPhone Simulator",
  "iPhone1,1": "iPhone 2G",
  "iPhone1,2": "iPhone 3G",
  "iPhone2,1": "iPhone 3GS",
  "iPhone3,1": "iPhone 4",
  "iPhone3,2": "iPhone 4",
  "iPhone3,3": "iPhone 4",
  "iPhone4,1": "iPhone 4S",
  "iPhone5,1": "iPhone 5",
  "iPhone5,2": "iPhone 5",
  "iPhone5,3": "iPhone 5C",
  "iPhone5,4": "iPhone 5C",
  "iPhone6,1": "iPhone 5S",
  "iPhone6,2": "iPhone 5S",
  "iPhone7,2": "iPhone 6",
  "iPhone7,1": "iPhone 6 Plus",
  "iPhone8,1": "iPhone 6S",
  "iPhone8,2": "iPhone 6S Plus",
  "iPhone8,4": "iPhone SE (1st generation)",
  "iPhone9,1": "iPhone 7",
  "iPhone9,3": "iPhone 7",
  "iPhone9,2": "iPhone 7 Plus",
  "iPhone9,4": "iPhone 7 Plus",
  "iPhone10,1": "iPhone 8",
  "iPhone10,4": "iPhone 8",
  "iPhone10,2": "iPhone 8 Plus",
  "iPhone10,5": "iPhone 8 Plus",
  "iPhone10,3": "iPhone X",
  "iPhone10,6": "iPhone X",
  "iPhone11,8": "iPhone XR",
  "iPhone11,2": "iPhone XS",
  "iPhone11,6": "iPhone XS Max",
  "iPhone11,4": "iPhone XS Max",
  "iPhone12,1": "iPhone 11",
  "iPhone12,3": "iPhone 11 Pro",
  "iPhone12,5": "iPhone 11 Pro Max",
  "iPhone12,8": "iPhone SE (2nd generation)",
  "iPhone13,1": "iPhone 12 mini",
  "iPhone13,2": "iPhone 12",
  "iPhone13,3": "iPhone 12 Pro",
  "iPhone13,4": "iPhone 12 Pro Max",
  "iPhone14,4": "iPhone 13 mini",
  "iPhone14,5": "iPhone 13",
  "iPhone14,2": "iPhone 13 Pro",
  "iPhone14,3": "iPhone 13 Pro Max",
  "iPhone14,6": "iPhone SE (3rd generation)",
  "iPhone14,7": "iPhone 14",
  "iPhone14,8": "iPhone 14 Plus",
  "iPhone15,2": "iPhone 14 Pro",
  "iPhone15,3": "iPhone 14 Pro Max",
  "iPhone15,4": "iPhone 15",
  "iPhone15,5": "iPhone 15 Plus",
  "iPhone15,6": "iPhone 15 Pro",
  "iPhone15,7": "iPhone 15 Pro Max",

  "iPad1,1": "iPad 1",
  "iPad2,1": "iPad 2",
  "iPad2,2": "iPad 2",
  "iPad2,3": "iPad 2",
  "iPad2,4": "iPad 2",
  "iPad3,1": "iPad 3",
  "iPad3,2": "iPad 3",
  "iPad3,3": "iPad 3",
  "iPad3,4": "iPad 4",
  "iPad3,5": "iPad 4",
  "iPad3,6": "iPad 4",
  "iPad4,1": "iPad Air",
  "iPad4,2": "iPad Air",
  "iPad4,3": "iPad Air",
  "iPad5,3": "iPad Air 2",
  "iPad5,4": "iPad Air 2",
  "iPad6,7": "iPad Pro 12.9-inch",
  "iPad6,8": "iPad Pro 12.9-inch",
  "iPad6,3": "iPad Pro 9.7-inch",
  "iPad6,4": "iPad Pro 9.7-inch",
  "iPad6,11": "iPad 5th generation",
  "iPad6,12": "iPad 5th generation",
  "iPad7,1": "iPad Pro 12.9-inch 2nd generation",
  "iPad7,2": "iPad Pro 12.9-inch 2nd generation",
  "iPad7,3": "iPad Pro 10.5-inch",
  "iPad7,4": "iPad Pro 10.5-inch",
  "iPad7,5": "iPad 6th generation",
  "iPad7,6": "iPad 6th generation",
  "iPad7,11": "iPad 7th generation",
  "iPad7,12": "iPad 7th generation",
  "iPad8,1": "iPad Pro 11-inch",
  "iPad8,2": "iPad Pro 11-inch",
  "iPad8,3": "iPad Pro 11-inch",
  "iPad8,4": "iPad Pro 11-inch",
  "iPad8,5": "iPad Pro 12.9-inch 3rd generation",
  "iPad8,6": "iPad Pro 12.9-inch 3rd generation",
  "iPad8,7": "iPad Pro 12.9-inch 3rd generation",
  "iPad8,8": "iPad Pro 12.9-inch 3rd generation",
  "iPad11,1": "iPad mini 5th generation",
  "iPad11,2": "iPad mini 5th generation",
  "iPad11,3": "iPad Air 3rd generation",
  "iPad11,4": "iPad Air 3rd generation",
  "iPad11,6": "iPad 8th generation",
  "iPad11,7": "iPad 8th generation",
  "iPad12,1": "iPad 9th generation",
  "iPad12,2": "iPad 9th generation",
  "iPad13,1": "iPad Air 4th generation",
  "iPad13,2": "iPad Air 4th generation",
  "iPad13,4": "iPad Pro 11-inch 3rd generation",
  "iPad13,5": "iPad Pro 11-inch 3rd generation",
  "iPad13,6": "iPad Pro 11-inch 3rd generation",
  "iPad13,7": "iPad Pro 11-inch 3rd generation",
  "iPad13,8": "iPad Pro 12.9-inch 5th generation",
  "iPad13,9": "iPad Pro 12.9-inch 5th generation",
  "iPad13,10": "iPad Pro 12.9-inch 5th generation",
  "iPad13,11": "iPad Pro 12.9-inch 5th generation",
  "iPad14,1": "iPad mini 6th generation",
  "iPad14,2": "iPad mini 6th generation",
  "iPad14,3": "iPad Pro 11-inch 4th generation",
  "iPad14,4": "iPad Pro 11-inch 4th generation",
  "iPad14,5": "iPad Pro 12.9-inch 6th generation",
  "iPad14,6": "iPad Pro 12.9-inch 6th generation",
};



